
/*
 *  
 *
 *  Copyright (C) Microsoft Corporation.  All rights reserved
 *
 *  
 */


using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;

namespace CRMScenarios
{
    /// <summary>
    /// Contains all the routines for registry handling
    /// </summary>
    static class Helper
    {
        static bool debug = false;
        static FileStream logFile = null;
        static StreamWriter writer = null;
        static string[][] BusinessEntities = null;
        private static ArrayList aListEntities = new ArrayList();


        /// <summary>
        /// Gets the registry key for the solution
        /// </summary>
        /// <returns></returns>
        private static RegistryKey GetRegistryKeyForOfficeCRM() //, bool write, bool create)
        {
            RegistryKey key = null;
            try
            {
                key = Registry.LocalMachine.OpenSubKey(@"software\microsoft\MSCRM\Office_Integration");
            }
            catch // any exception.
            {
                System.Windows.Forms.MessageBox.Show(global::CRMScenarios.Resources.InstallationCorrupted);
            }
            return key;
        }
        public static ArrayList GetCRMEntities()
        {
            bool fCacheFull = false;
            ArrayList aListEntitiesAccessed = OfficeApi.GetRecentlyAccessedEntities();
            if (aListEntitiesAccessed.Count == 4)
                fCacheFull = true;//If recently accessed entities are 4 already then we won't get from config file.

            if (!fCacheFull)
            {
                string TargetServerURL = CacheManager.GerServerURL(string.Empty);
                bool login = CrmConnector.Login(TargetServerURL);

                if (login)
                {
                    BusinessEntities = CrmConnector.getEntityListFromCRM(PrivilegeType.Read);
                    string[] entityList = null;
                    if ((BusinessEntities == null) || ((entityList = BusinessEntities[0]) == null) || (entityList.Length == 0))
                    {
                        MessageBox.Show(global::CRMScenarios.Resources.NoEntitiesConfigured, ResFixer.Resources.LoadString("strWarning"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return null;
                    }
                    if (entityList != null)
                        aListEntities.AddRange(entityList);
                }
                else
                {
                   // MessageBox.Show(ResFixer.Resources.LoadString("ErrorGettingCRMEntities"), ResFixer.Resources.LoadString("strError"));
                    return null;
                }


            }
            int iCountMainList = 4;
            if (aListEntities.Count < 4)
                iCountMainList = aListEntities.Count;

            string strNameToAdd = string.Empty;
            foreach (string strNameInMain in aListEntities)
            {
                bool fNamePresent = false;
                foreach (string sreNameSec in aListEntitiesAccessed)
                {
                    if (strNameInMain.Equals(sreNameSec))
                        fNamePresent = true;
                }
                if (!fNamePresent)
                {
                    if (aListEntitiesAccessed.Count < iCountMainList)
                        aListEntitiesAccessed.Add(strNameInMain);
                    else
                        break;
                }
            }
            return aListEntitiesAccessed;



        }
        /// <summary>
        /// Gets the install path of the solution
        /// </summary>
        /// <param name="defaultResult"></param>
        /// <returns></returns>
        public static string GetInstallPath(string defaultResult)
        {
            RegistryKey key = null;
            string strInstPath = defaultResult;
            try
            {
                key = GetRegistryKeyForOfficeCRM();
                strInstPath = (string)key.GetValue("InstPath", defaultResult);
            }
            catch { }
            key.Close();
            return strInstPath;
        }

        /// <summary>
        /// checks whether the file is in a temporary location
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool IsTempFile(string path)
        {
            if ((path == null) || (path.Length == 0))
            {
                return false;
            }

            string tempLocation = System.IO.Path.GetTempPath();
            string tempLocWithoutSlash = tempLocation.Substring(0, tempLocation.Length - 2);
            if (path.IndexOf(tempLocWithoutSlash, System.StringComparison.InvariantCulture) == 0)
            {               
                return true;
            }

            return false;
        }

        /// <summary>
        /// Get the value of traceaddin key in the registry
        /// </summary>
        /// <returns></returns>
        public static bool GetTrace()
        {
            RegistryKey key = null;
            string str = null;
            try
            {
                key = GetRegistryKeyForOfficeCRM();
                str = (string)key.GetValue("TraceAddin", null);
            }
            catch { }
            key.Close();

            if (str != null)
            {
                debug = true;
                try
                {
                    logFile = new FileStream("C:\\crmoffintlogfile.txt", FileMode.Create, FileAccess.ReadWrite);
                    writer = new StreamWriter(logFile);
                }
                catch (Exception traceExp)
                {
                    MessageBox.Show(LocalResources.TracerInitialize + traceExp.Message); // NO LOCALIZATION
                    return false;
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Do tracing. Print the message to user if needed.
        /// </summary>
        /// <param name="str"></param>
        /// <param name="box"></param>
        public static void Trace(string str, bool box)
        {
            if (debug)
            {
                if (box)
                {
                    MessageBox.Show(str, LocalResources.HelperTrace, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                try
                {
                    writer.WriteLine(str);
                    writer.Flush();
                    logFile.Flush();
                }
                catch (Exception writeExp)
                {
                    MessageBox.Show(LocalResources.LogFileError + writeExp.Message); // NO LOCALIZATION
                }
            }
        }
    }
}
